<?php
namespace app\system\controller;

use app\common\model\Details;
use app\common\model\Region;
use app\system\model\GroupLinkModel;
use app\system\model\LinkModel;
use app\system\model\ManageModel;
use app\system\model\NewClassModel;
use app\system\validate\Manager;
use think\db;

class Index extends Common
{

    
    /**
     * @return mixed
     * @throws \think\exception\DbException
     * @throws db\exception\DataNotFoundException
     * @throws db\exception\ModelNotFoundException
     */
    public function index()
    {
        $manageInfo = session('manageInfo');

        //用户拥有的连接导航
        $groupLinkModel = new GroupLinkModel();
        $linkId = $groupLinkModel->getGroupLinkFieldList(['group_id'=>$manageInfo['group_id']], 'link_id');

        $linkModel = new LinkModel();
        $link = $linkModel->selectLink(['id'=>['in', $linkId],'is_delete'=>0]);
        $link = obj2array($link);
        $link = classnav(systemNav($link));
        //文章分类
        $newClassModel = new NewClassModel();
        $newclass = $newClassModel->selectNewClass([], 'sort desc,id desc');
        $newclass = obj2array($newclass);
        $newclass = classnav(newClassNav($newclass, 0, 1));

        //区域信息
        $areaModel = new Region();
        $shengList = $areaModel->selectRegion();
        $cityList = $areaModel->selectRegion(['pid'=>$manageInfo['sheng_id']]);
        $areaList = $areaModel->selectRegion(['pid'=>$manageInfo['city_id']]);

        $assign = [
            'manageInfo' => $manageInfo,
            'shengList' => $shengList,
            'cityList' => $cityList,
            'areaList' => $areaList,
            'link' => $link,
            'newclass' => $newclass,
        ];

        return $this->fetch('', $assign);
    }

    /**
     * @return mixed
     * @throws \think\exception\PDOException
     * @throws db\exception\BindParamException
     */
    public function panel()
    {
//        $year = input('get.year', 0, 'intval');
//        $month = $this->getMonthArray($year);

        //从服务器中获取GD库的信息
        if(function_exists("gd_info")){
            $gd = gd_info();
            $gdinfo = $gd['GD Version'];
        }else {
            $gdinfo = "未知";
        }
        //获取MySQL数据库版本信息
        $version = db()->query("select version() as ver");
        $assign = [
            'manageInfo' => session('manageInfo'),
            'sysos' => $_SERVER["SERVER_SOFTWARE"],  //获取服务器标识的字串
            'sysversion' => PHP_VERSION,  //获取PHP服务器版本
            'mysqlos' => $version[0]['ver'],
            'gdinfo' => $gdinfo,
            'max_upload' => ini_get("file_uploads") ? ini_get("upload_max_filesize") : "Disabled",  //从PHP配置文件中获得最大上传限制
            'max_ex_time' => ini_get("max_execution_time")."秒"  //从PHP配置文件中获得脚本的最大执行时间
        ];

        return $this->fetch('', $assign);
    }

    private function getMonthArray($year)
    {
        if ($year) {
            for ($i = 1 ; $i <= 12 ; $i ++ ) {
                $day = $this->yearMonthDay($year, $i);

                $month[] = [
                    'years' => $year ,
                    'month' => $i,
                    'day' => $day, //当月的天数
                    'min' => strtotime($year . '-' . $i . '-1 00:00:01'), //当月最小时间戳
                    'max' => strtotime($year . '-' . $i . '-' . $day . ' 23:59:59'), //当月最大时间戳
                ];
            }
        } else {
            //获取现在开始往前数一年的每个月
            $months = intval(date('m'));
            $years = intval(date('Y',time()));
            for($i = $months+1 ; $i!=$months ; $i++){
                if ($i == 13) {
                    $i = 1;
                    $years++;
                }

                $day = $this->yearMonthDay($years-1, $i);

                $month[] = [
                    'years' => $years-1,
                    'month' => $i,
                    'day' => $day, //当月的天数
                    'min' => strtotime(($years-1) . '-' . $i . '-1 00:00:01'), //当月最小时间戳
                    'max' => strtotime(($years-1) . '-' . $i . '-' . $day . ' 23:59:59'), //当月最大时间戳
                ];
            }
        }
        return $month;
    }

    /*
     * 获得某一年某一月有多少天
     * */
    private function yearMonthDay($year,$month){
        return date('j',mktime(0,0,1,($month==12?1:$month+1),1,($month==12?$year+1:$year))-24*3600);
    }

    public function getAjaxRegion()
    {
        $id = input('get.id', 0, 'intval');
        $areaModel = new Region();
        $areaList = $areaModel->selectRegion(['pid'=>$id]);
        return $this->jsonSuccess('succ', $areaList);
    }

    /**
     * 修改资料
     * */
    public function saveInfo()
    {
        !isAjaxPost() && die();
        $data = input('post.');
        $data['id'] = session('manageInfo.id');

        $model = new ManageModel();
        //表单自动验证
        $validate = new Manager();
        if (!$validate->scene('info')->check($data)) {
            return $this->jsonError($validate->getError());
        }

        if ($model->updateManage($data, ['id'=>session('manageInfo.id')]) !== false) {
//            $manageInfo = $model->findManage(['id' => session('manageInfo.id')])->toArray();
            session('manageInfo', array_merge(session('manageInfo'), $data));
            return $this->jsonSuccess('修改成功!');
        } else {
            return $this->jsonError('修改失败!');
        }
    }

    /**
     * 修改密码
     * */
    public function savePass()
    {
        !isAjaxPost() && die();
        $where['id'] = session('manageInfo.id');
        $where['password'] = passmd(input('post.password', '', 'trim'));

        $model = new ManageModel();
        if ($model->where($where)->count() <= 0) {
            return $this->jsonError('原密码输入错误！', $where);
        }

        $one = input('post.onepassword', '', 'trim');
        $two = input('post.twopassword', '', 'trim');
        if (!empty($one) && $one != $two) {
            return $this->jsonError('新密码输入不一样，请重新输入！');
        }
        if ($model->updateManage(['password'=>passmd($one)], ['id'=>$where['id']]) !== false) {
            session('manageInfo', null);
            return $this->jsonSuccess('密码已重置，请重新登陆！');
        } else {
            return $this->jsonError('操作失败！');
        }
    }

    /**
     * 自动执行 积分转结
     * @throws \think\Exception
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     * @throws db\exception\DataNotFoundException
     * @throws db\exception\ModelNotFoundException
     */
    public function autoIntegral()
    {
        set_time_limit(0);
        $limit = 100;
        $params = getSystemParams();
        $days = $params['auto_days'];
        $integral_rate = $params['integral_rate'];
        $details_model = new Details();
        while ($list = $details_model->where(['type'=>6,'status'=>0,'add_time'=>['elt', time()-86400*$days]])->limit(0, $limit)->select()) {
            foreach ($list as $v) {
                db::startTrans();
                if ($details_model->where(['id'=>$v['id']])->setField('status', 1) === false) {
                    db::rollback();
                    continue;
                }
                //积分转结金额
                $amount = amountFormat($v['amount'] / $integral_rate);
                $data = [
                    'balance' => ['exp', '`balance` + '.$amount],
                    'integral' => ['exp', '`integral` - '.$v['amount']]
                ];
                if ($v['user_type'] == 1) {
                    //商家
                    //加余额减积分
                    if (db::name('business')->where(['user_id'=>$v['user_id']])->update($data) === false) {
                        db::rollback();
                        continue;
                    }
                    $info = db::name('business')->where('user_id', $v['user_id'])->field('balance,integral')->find();
                } else {
                    //用户
                    //加余额减积分
                    if (db::name('user')->where(['id'=>$v['user_id']])->update($data) === false) {
                        db::rollback();
                        continue;
                    }
                    $info = db::name('business')->where('user_id', $v['user_id'])->field('balance,integral')->find();
                }
                //资金记录
                //加余额
                $log[] = [
                    'content' => '积分转结',
                    'amount' => $amount,
                    'add_time' => time(),
                    'user_id' => $v['user_id'],
                    'user_type' => $v['user_type'],
                    'type' => 3,
                    'symbol' => '+',
                    'balance' => $info['balance']
                ];
                //减积分
                $log[] = [
                    'content' => '积分转结',
                    'amount' => $v['integral'],
                    'add_time' => time(),
                    'user_id' => $v['user_id'],
                    'user_type' => $v['user_type'],
                    'type' => 7,
                    'symbol' => '-',
                    'balance' => $info['integral']
                ];
                if (!$details_model->insertAll($log)) {
                    db::rollback();
                    continue;
                }
                db::commit();
            }
        }
    }

    /**
     * 自动收货
     * @throws \think\Exception
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     * @throws db\exception\DataNotFoundException
     * @throws db\exception\ModelNotFoundException
     */
    public function autoOrder() {
        die;
        set_time_limit(0);
        $limit = 100;
        $params = getSystemParams();
        $days_confirm = isset($params['auto_days_order_confirm']) ? $params['auto_days_order_confirm'] : 0;
        $days_close = isset($params['auto_days_order_close']) ? $params['auto_days_order_close'] : 0;
        $order_model = new \app\common\model\Order();
        //系统自动关闭订单
        if ($days_close > 0) {
            $order_model->where(['status' => 1, 'add_time' => ['elt', time() - 86400 * $days_close]])->setField('status', '9');
        }
        $days_confirm <= 0 && die;
        //收货
        while ($list = $order_model->where(['status'=>3,'send_time'=>['elt', time() - 86400 * $days_confirm]])->limit(0, $limit)->select()) {
            foreach ($list as $v) {
                $order_model->startTrans();
                if ($order_model->where(['id'=>$v['id']])->setField('status', 4) === false) {
                    $order_model->rollback();
                    continue;
                }

                //分销计算
                $pid = db::name('user')->where(['id'=>$v['user_id']])->value('pid');
                if (!calFxEarnings($v['amount'], $pid)) {
                    $order_model->rollback();
                    continue;
                }
                if (!addPrevFxAmount($v['amount'], $pid)) {
                    $order_model->rollback();
                    continue;
                }

                $order_model->commit();
            }
        }
    }

    /**
     * @throws \think\Exception
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     * @throws db\exception\DataNotFoundException
     * @throws db\exception\ModelNotFoundException
     */
    public function autoCal() {
        set_time_limit(0);
        $limit = 3;
        $params = getSystemParams();
        $user_model = new \app\common\model\User();
        $i=0;
        if ($user_model->where(['date1'=>['neq', date('Y-m')]])->count() > 0) {
            $update1 = [
                'date1' => date('Y-m'),
                'role' => 1
            ];
            $update2 = [
                'date1' => date('Y-m'),
                'role' => 0
            ];
            //主管
            while (
            $list = $user_model
                ->where(['date1'=>['neq',date('Y-m')]])
                ->field('id')
                ->limit(0, $limit)
                ->select()
            ) {
                $ids1 = $ids2 = [];

                foreach ($list as $v) {
                    $v = $v->toArray();
                    $v['amount'] = db::name('history_tg')->where(['date'=>date('Y-m', strtotime('-1 month'))])->value('amount');
                    if ($v['amount'] > $params['zg_amount'] * date('t', strtotime('-1 month'))) {
                        $ids1[] = $v['id'];
                    } else {
                        $ids2[] = $v['id'];
                    }
                }

                if (!empty($ids1)) {
                    db::name('user')->where(['id'=>['in',$ids1]])->update($update1);
                }
                if (!empty($ids2)) {
                    db::name('user')->where(['id'=>['in',$ids2]])->update($update2);
                }
                if ($i>=5) {
                    die;
                }
                $i++;
            }
        } else if ($user_model->where(['date2'=>['neq', date('Y-m')]])->count() > 0) {
            $update1 = [
                'date2' => date('Y-m'),
                'role' => 2
            ];
            $update2 = [
                'date2' => date('Y-m'),
            ];
            //经理
            while ($list = $user_model->where(['date2'=>['neq', date('Y-m')]])->limit(0, $limit)->select()) {
                $ids1 = $ids2 = [];
                foreach ($list as $v) {
                    $v = $v->toArray();
                    //一代
                    $one = getFxData($v['id'], false);
                    $two = $three = [
                        'num' => 0, 'amount' => 0
                    ];
                    if ($one['num'] > 0) {
                        $two = getFxData($one['ids'], false);
                        if ($two['num'] > 0) {
                            $three = getFxData($two['ids'], false);
                        }
                    }
                    $ids = array_merge(empty($one['ids']) ? [] : $one['ids'], empty($two['ids']) ? [] : $two['ids'], empty($three['ids']) ? [] : $three['ids']);
                    if ($user_model->where(['id'=>['in', $ids],'role'=>1])->count() > $params['zg_num']) {
                        $ids1[] = $v['id'];
                    } else {
                        $ids2[] = $v['id'];
                    }
                }
                if (!empty($ids1)) {
                    db::name('user')->where(['id'=>['in',$ids1]])->update($update1);
                }
                if (!empty($ids2)) {
                    db::name('user')->where(['id'=>['in',$ids2]])->update($update2);
                }
                if ($i>=3) {
                    die;
                }
                $i++;
            }
        } else if ($user_model->where(['date3'=>['neq', date('Y-m')]])->count() > 0) {
            $update1 = [
                'date3' => date('Y-m'),
                'role' => 3
            ];
            $update2 = [
                'date3' => date('Y-m'),
            ];
            //总监
            while ($list = $user_model->where(['date3'=>['neq', date('Y-m')]])->limit(0, $limit)->select()) {
                $ids1 = $ids2 = [];
                foreach ($list as $v) {
                    $v = $v->toArray();
                    //一代
                    $one = getFxData($v['id'], false);
                    $two = $three = [
                        'num' => 0, 'amount' => 0
                    ];
                    if ($one['num'] > 0) {
                        $two = getFxData($one['ids'], false);
                        if ($two['num'] > 0) {
                            $three = getFxData($two['ids'], false);
                        }
                    }
                    $ids = array_merge(empty($one['ids']) ? [] : $one['ids'], empty($two['ids']) ? [] : $two['ids'], empty($three['ids']) ? [] : $three['ids']);
                    if ($user_model->where(['id'=>['in', $ids],'role'=>2])->count() > $params['jl_num']) {
                        $ids1[] = $v['id'];
                    } else {
                        $ids2[] = $v['id'];
                    }
                }
                if (!empty($ids1)) {
                    db::name('user')->where(['id'=>['in',$ids1]])->update($update1);
                }
                if (!empty($ids2)) {
                    db::name('user')->where(['id'=>['in',$ids2]])->update($update2);
                }
                if ($i>=3) {die;
                }
                $i++;
            }
        }

    }

}
